package utils

import (
	"github.com/jinzhu/gorm"
)

type PageReq struct {
	PageSize int64 `json:"pageSize"` // 每页条数
	Page     int64 `json:"page"`     // 页码
}

// 用户分页查询条件
type UserPageReq struct {
	Name string `json:"name"`
	PageReq
}

type Pager struct {
	Count       int64       `json:"count"`
	CurrentPage int64       `json:"currentPage"`
	Data        interface{} `json:"data"`
	PageSize    int64       `json:"pageSize"`
	TotalPages  int64       `json:"totalPages"`
}

func Paginate(req PageReq) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if req.Page == 0 {
			req.Page = 1
		}
		pageSize := req.PageSize
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (req.Page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
